﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using WorkItemAnalyser.Core.Parsers;

namespace WorkItemAnalyser.Core
{
    public class RuleExecutor<TRuleInput>
    {
        private readonly IRuleParser<TRuleInput> parser;

        public RuleExecutor(IRuleParser<TRuleInput> parser)
        {
            this.parser = parser;
        }

        public IEnumerable<AssertionResult> Execute(TRuleInput ruleInput)
        {
            return Execute(ruleInput, null);
        }

        public IEnumerable<AssertionResult> Execute(TRuleInput ruleInput, IEnumerable<WorkItem> workItems)
        {
            var rules = parser.RetrieveRules(ruleInput);
            return rules
                .SelectMany(r =>
                                {
                                    var workItemsToAssertAgainst = ExecuteQuery(workItems, r.Query);
                                    return r.Assertion.Execute(workItemsToAssertAgainst);
                                });
        }

        private IEnumerable<WorkItem> ExecuteQuery(IEnumerable<WorkItem> workItems, Query query)
        {
            return
                workItems.Where(
                    workItem =>
                    (workItem.Project.Name.Equals(query.TeamProjectName, StringComparison.OrdinalIgnoreCase)) &&
                    (workItem.Type.Name.Equals(query.WorkItemType, StringComparison.OrdinalIgnoreCase)));
        }
    }
}